package com.sunfeng.netty.atguigu.codec4;

import com.google.protobuf.TextFormat;
import com.sunfeng.netty.atguigu.codec3.SubscribeResp;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author sunfeng
 * @date 2021/05/19 16:53
 **/
@Slf4j
@ChannelHandler.Sharable
public class SubReqProtoServerHandler extends SimpleChannelInboundHandler<SubScribeReqProto.SubScribeReq> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SubScribeReqProto.SubScribeReq subScribeReq) throws Exception {
        if ("SunFeng".equalsIgnoreCase(subScribeReq.getUserName())) {
            System.out.println("服务端接收到客户端数据" + TextFormat.printToUnicodeString(subScribeReq) );
            ctx.writeAndFlush(resp(subScribeReq.getSubReqID()));
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.debug(cause.getMessage());
        ctx.close();
    }

    private SubscribeRespProto.SubscribeResp resp(int subReqID) {
        SubscribeRespProto.SubscribeResp.Builder  builder = SubscribeRespProto.SubscribeResp.newBuilder();
        builder.setSubReqID(subReqID);
        builder.setRespCode(0);
        builder.setDesc("Netty 成功了~~~ 三天后,发货到你这个地址");
        return builder.build();
    }
}
